package com.sunagy.demand.backend.service.impl;

import com.sunagy.demand.backend.VO.request.ProductAddRequestVO;
import com.sunagy.demand.backend.VO.request.ProductEditRequestVO;
import com.sunagy.demand.backend.entity.Product;
import com.sunagy.demand.backend.VO.response.ProductResponseVO;
import com.sunagy.demand.backend.repository.ProductRepository;
import com.sunagy.demand.backend.service.ProductService;
import com.sunagy.demand.backend.utils.BeanUtil;
import com.sunagy.demand.backend.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/5/8
 * time：下午5:35
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;
    @Override
    public List<ProductResponseVO> getTree() {
        List<Product> productList = productRepository.findAll();
        List<ProductResponseVO> productResponseVOList = (List<ProductResponseVO>) BeanUtil.copyPropertiesList(productList,ProductResponseVO.class);
        productResponseVOList = TreeUtil.buildByRecursive(productResponseVOList,-1);
        return productResponseVOList;
    }

    @Override
    public List<ProductResponseVO> getList() {
        List<Product> productList = productRepository.findAll();
        List<ProductResponseVO> productResponseVOList = (List<ProductResponseVO>) BeanUtil.copyPropertiesList(productList,ProductResponseVO.class);
        return productResponseVOList;
    }

    @Override
    @Transactional
    public ProductResponseVO add(ProductAddRequestVO productAddRequestVO) {
        ProductResponseVO productResponseVO = new ProductResponseVO();
        Product product = new Product();
        BeanUtil.copyProperties(product,productAddRequestVO);
        BeanUtils.copyProperties(productRepository.save(product), productResponseVO);
        return productResponseVO;
    }

    @Override
    @Transactional
    public ProductResponseVO edit(Integer id, ProductEditRequestVO productEditRequestVO) {
        ProductResponseVO productResponseVO = new ProductResponseVO();
        Product product = productRepository.findOne(id);
        BeanUtil.copyProperties(product,productEditRequestVO);
        BeanUtils.copyProperties(productRepository.save(product), productResponseVO);
        return productResponseVO;
    }

    @Override
    @Transactional
    public Integer del(Integer id) {
        productRepository.delete(id);
        return id;
    }

}
